import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getSigns, getEndedSigns } from '@/api/sign'

export const useSignsStore = defineStore('signs', () => {
    // 状态
    const signs = ref([])
    const total = ref(0)
    const pageNum = ref(1)
    const pageSize = ref(10)
    const dateRange = ref(['', ''])
    const sortBy = ref('desc')
    const loading = ref(false)
    const searchText = ref('')
    const status = ref('all')

    // 获取签到列表
    const fetchSigns = async () => {
        loading.value = true
        try {
            const params = {
                pageNum: pageNum.value,
                pageSize: pageSize.value,
                sortType: sortBy.value,
                startDate: dateRange.value[0],
                endDate: dateRange.value[1],
                searchText: searchText.value,
                status: status.value
            }
            const res = await getSigns(params)
            signs.value = res.data.items
            total.value = res.data.total
        } catch (error) {
            console.error('获取签到列表失败:', error)
        } finally {
            loading.value = false
        }
    }

    // 获取已结束的签到列表
    const fetchEndedSigns = async () => {
        loading.value = true
        try {
            const params = {
                pageNum: pageNum.value,
                pageSize: pageSize.value,
                sortType: sortBy.value,
                startDate: dateRange.value[0],
                endDate: dateRange.value[1],
                searchText: searchText.value,
                status: status.value
            }
            const res = await getEndedSigns(params)
            signs.value = res.data.items
            total.value = res.data.total
        } catch (error) {
            console.error('获取已结束的签到列表失败:', error)
        } finally {
            loading.value = false
        }
    }

    // 重置筛选条件
    const resetFilters = () => {
        dateRange.value = ['', '']
        sortBy.value = 'desc'
        searchText.value = ''
        status.value = 'all'
        pageNum.value = 1
        pageSize.value = 10
    }

    return {
        signs,
        total,
        pageNum,
        pageSize,
        dateRange,
        sortBy,
        loading,
        searchText,
        status,
        fetchSigns,
        fetchEndedSigns,
        resetFilters
    }
})
